package org.javaexpert.spaces.masterworker.ui.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.*;
import com.gwtext.client.data.event.StoreListenerAdapter;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.grid.*;
import com.gwtext.client.widgets.grid.event.GridRowListenerAdapter;

import java.util.Date;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class TaskList implements EntryPoint {

    SpacesStatsServiceAsync statsService;
    private TaskStatusData[] tsds;
    private long lastLoad;
    private boolean hideFinished = false;
    private DynaTableWidget table;
    private Grid grid;

    public TaskList() {
        //
        statsService = (SpacesStatsServiceAsync) GWT.create(SpacesStatsService.class);

        // By default, we assume we'll make RPCs to a servlet, but see
        // updateRowData(). There is special support for canned RPC responses.
        // (Which is a totally demo hack, by the way :-)
        //
        ServiceDefTarget target = (ServiceDefTarget) statsService;

        // Use a module-relative URLs to ensure that this client code can find
        // its way home, even when the URL changes (as might happen when you
        // deploy this as a webapp under an external servlet container).
        String moduleRelativeURL = GWT.getModuleBaseURL() + "spacesStats";
        target.setServiceEntryPoint(moduleRelativeURL);
    }

    /**
     * This is the entry point method.
     */


    public void onModuleLoad() {

        String[] columns = {"Id", "Status", "Finished", "RetryCount", "Start", "End", "Comment"};
        String[] styles = null;
//        table = initTable(columns, styles);

        RootPanel.get().add(initButton());
        RootPanel.get().add(abc());
    }

    private DynaTableWidget initTable(String[] columns, String[] styles) {
        return new DynaTableWidget(new DynaTableDataProvider() {
            public void updateRowData(final int startRow, final int maxRows, final RowDataAcceptor acceptor) {
                if (tsds == null || System.currentTimeMillis() - lastLoad > 10L * 1000) {
                    statsService.getTaskStatuses(hideFinished, new AsyncCallback() {
                        public void onFailure(Throwable caught) {
                            acceptor.failed(caught);
                        }

                        public void onSuccess(Object result) {
                            tsds = (TaskStatusData[]) result;
                            lastLoad = System.currentTimeMillis();
                            pushData(acceptor, startRow, maxRows);
                        }
                    });
                } else {
                    pushData(acceptor, startRow, maxRows);
                }
            }
        }, columns, styles, 50);
    }

    private CheckBox initButton() {
        final CheckBox button = new CheckBox("Toggle Finished");
        button.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                hideFinished = button.isChecked();
                tsds = null;
                table.refresh();
            }
        });
        return button;
    }

    private void pushData(DynaTableDataProvider.RowDataAcceptor acceptor, int startRow, final int max) {
        String[][] res = new String[max][7];
        for (int i = startRow; i < tsds.length && i - startRow < max; i++) {
            res[i - startRow][0] = tsds[i].taskId.toString();
            res[i - startRow][1] = tsds[i].status;
            res[i - startRow][2] = ""+tsds[i].finished;
            res[i - startRow][3] = ""+tsds[i].retryCount;
            res[i - startRow][4] = ""+tsds[i].startTime;
            res[i - startRow][5] = ""+tsds[i].finishTime;
            res[i - startRow][6] = tsds[i].comment;
        }
        acceptor.accept(startRow, res);
    }

    Grid abc(){
        MemoryProxy proxy = new MemoryProxy(new Object[][]{
                new Object[]{"10", "true"},
                new Object[]{"12", "false"}});
        Store store = new Store(proxy, new ArrayReader( new RecordDef(new FieldDef[]{
                        new StringFieldDef("id"),
                        new StringFieldDef("finished") })));

        //when the store is loaded, select the first row
        store.addStoreListener(new StoreListenerAdapter() {
            public void onLoad(Store store, Record[] records) {
                if (records != null && records.length > 0) {
                    grid.getSelectionModel().selectFirstRow();
                }
            }
        });
        store.load();

        //initial sort order
        store.setDefaultSort("id", "DESC");

        //setup column model for the grid along with formatting options
        ColumnModel cm = new ColumnModel(new ColumnConfig[]{
                new ColumnConfig() {
                    {
                        setId("id");
                        setHeader("Id");
                        setDataIndex("id");
                        setSortable(true);
                        setWidth(420);
                    }
                },
                new ColumnConfig() {
                    {
                        setId("finished");
                        setHeader("Finished");
                        setDataIndex("finished");
                        setSortable(true);
                        setWidth(50);
                    }
                }
        });

        //create and render grid
        grid = new Grid("topic-grid", "100%", "100%", store, cm, new GridConfig() {
            {
                setAutoExpandColumn("title");
            }
        });
        grid.render();
        return grid;
        //add listener for context menu when user right clicks on a row
//        grid.addGridRowListener(new GridRowListenerAdapter() {
//            public void onRowContextMenu(Grid grid, int rowIndex, EventObject e) {
//                if (gridMenu == null) {
//                    createGridMenu();
//                }
//                e.stopEvent();
//                ctxRecord = grid.getStore().getAt(rowIndex);
//                gridMenu.showAt(e.getXY());
//            }
//        });

    }
}
